package com.xz.xzmybatisagent;

import java.lang.instrument.Instrumentation;

/**
 * @author DONG.WANG17@HAND-CHINA.COM
 * @since 2025-02-13 16:55
 */
public class PremainAgent {
    public static void premain(String agentArgs, Instrumentation inst) {
        System.out.println("开始执行 PremainAgent 代理程序...");
        InterceptorClassFileTransformer interceptorClassFileTransformer = new InterceptorClassFileTransformer();
        // 在代理参数中获取进程通信的 port
        interceptorClassFileTransformer.setArgs(agentArgs);
        inst.addTransformer(interceptorClassFileTransformer, true);

        // 主动触发retransform
        Class<?>[] classes = inst.getAllLoadedClasses();
        for (Class<?> clazz : classes) {
            if (clazz.getName().equals("org.apache.ibatis.plugin.InterceptorChain")) {
                System.out.println("premain ----------- retransformClasses");
                try {
                    inst.retransformClasses(clazz);
                } catch (Throwable t) {
                    System.err.println("premain ----------- retransformClasses error: " + t.getMessage());
                }
            }
        }
    }

    //如果代理类没有成功，那么 JVM 将尝试调用该方法
    public static void premain(String agentArgs) {
    }
}
